package tree;

import everyday.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 给定一个单链表，其中的元素按升序排序，将其转换为高度平衡的二叉搜索树。
 * 本题中，一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1
 * @author le
 */
public class ConvertSortedListToBinarySearchTree
{
    public static void main(String[] args)
    {

    }

    public TreeNode sortedListToBST(ListNode head) {
        if (head == null){
            return null;
        }
        List<Integer> res = new ArrayList<>();
        while(head != null){
            res.add(head.val);
            head = head.next;
        }
        int[] nums = new int[res.size()];
        int index = 0;
        for(int item : res){
            nums[index] = item;
            index++;
        }
        return helper(nums, 0, nums.length-1);
    }

    private TreeNode helper(int[] nums,int low,int high){
        if (low > high){
            return null;
        }
        int mid = (high + low) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(nums, low, mid-1);
        root.right = helper(nums, mid+1, high);
        return root;
    }
}
